package deadlock

import "fmt"
import "dumpwave"
const (
	BYTE_0 = iota;
	BYTE_1;
	BYTE_2;
	BYTE_3;
	BYTE_01;
	BYTE_23;
	BYTE_012;
	BYTE_123;
	BYTE_ALL;
)

func Memory (
	load        chan int32,
	pc_addr     chan uint32,
	instruction chan uint32,
	ls_addr     chan uint32,
	ls_rw       chan bool,
	ls_data_in  chan int32,
	ls_data_out chan int32) {

	var (
		vData int32
		vAddr uint32
		vRW   bool
	)

	chAddr := make(chan uint32)
	chWrite := make(chan bool)
	chDataToRam := make(chan int32)
	chDataFromRam := make(chan int32)
	//instruction := make(chan int32)
	//ls_data_out	:= make(chan int32)
	//load := make(chan int32)

	fmt.Println("[MEM] Starting ram...");
	go RAM(chAddr, chWrite, chDataToRam, chDataFromRam)
	fmt.Println("[MEM] Return of ram...")

	// loading memory
	fmt.Println("[MEM] Waiting memory load")
	vAddr = 0
	for vData = range load {
		chAddr <- vAddr
		chWrite <- true
		chDataToRam <- vData
		vAddr++
	}

    fmt.Println("[MEM] Load finished")
    fmt.Println("[MEM] Normal operation started")
    
    
    // memory start working*/
	for {
		select {
		case vAddr = <-pc_addr :
			fmt.Println("[MEM] Accessing Instruction")
			chAddr <- vAddr
			chWrite <- false
			vData = <-chDataFromRam
		fmt.Printf("[MEM] Sending Instruction 0x%x @ 0x%x\n", uint32(vData), vAddr)	
			dumpwave.Wave(1,"req_ack_INST")				//dumpWave	
			dumpwave.Wave(int(vData),"cha_INST")			//dumpWave
			instruction <- uint32(vData)
			dumpwave.Wave(0,"req_ack_INST")				//dumpWave
		fmt.Println("[MEM] Instruction sent")

		case vAddr = <-ls_addr :
			fmt.Println("[MEM] Accessind Data Memory")
			vRW = <-ls_rw
			if (vRW) { //write na memoria
				vData = <-ls_data_in
				fmt.Println("[MEM] Wrint32ing ", vData, " @ ", vAddr)
				chAddr <- vAddr
				chWrite <- vRW
				chDataToRam <- vData
			} else {
				chAddr <- vAddr
				chWrite <- vRW
				vData = <-chDataFromRam
				dumpwave.Wave(1,"req_ack_LS_DATA_OUT")		//dumpWave
				dumpwave.Wave(int(vData),"cha_LS_DATA_OUT")	//dumpWave
				ls_data_out <- vData
				dumpwave.Wave(0,"req_ack_LS_DATA_OUT")		//dumpWave
			}
		}
	} // end infinite loop
}

